"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 数据库启动前，设置的审计日志路径目录无效,数据库启动失败
Create At   : 2020/06/28
@zou_jialiang0505328126
Description :
    1.修改配置文件中的审计目录为无权限
    2.启动数据库
    3.恢复权限
Expect      :
    1.修改成功
    2.启动失败
    3.恢复权限成功
History     :
    modified by @wan005 at 2022.09.14:优化期望及teardown
"""

import os
import unittest
import sys
import time
from yat.test import macro
from yat.test import Node

sys.path.append(sys.path[0] + "/../")
from testcase.utils.PgSql import PgSql
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common


class Modifyauditfilepermission(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case054.py start------------')
        self.rootNode = Node()
        self.dbUserNode = Node(node='dbuser')
        self.PG_AUDIT_PATH = macro.PG_AUDIT_PATH
        self.com = Common()

        self.log.info('stop opengauss')
        is_stoped = self.sh.stopDbCluster()
        self.assertTrue(is_stoped)

    def test_Modify_Table_File_Permission(self):
        chmodfile_cmd = 'chmod -R 000 ' + self.PG_AUDIT_PATH
        self.log.info(chmodfile_cmd)
        self.rootNode.sh(chmodfile_cmd)

        time.sleep(3)

        db_status = self.sh.getDbClusterStatus('status')
        self.assertFalse(db_status)

        time.sleep(3)

        # 启动数据库
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

        chmodfile_cmd = 'chmod -R 700 ' + self.PG_AUDIT_PATH
        self.log.info(chmodfile_cmd)
        self.rootNode.sh(chmodfile_cmd)

        time.sleep(3)

    def tearDown(self):
        self.log.info('this is tearDown')
        chmodfile_cmd = 'chmod -R 700 ' + self.PG_AUDIT_PATH
        self.log.info(chmodfile_cmd)
        self.rootNode.sh(chmodfile_cmd)
        time.sleep(3)
        self.sh.startDbCluster()

        db_status = self.sh.getDbClusterStatus('status')
        if not db_status:
            raise Exception("db status is not true, please check!")
        self.log.info(db_status)
